<template>
    <section>
        <!--工具条-->
        <el-col :span="24" class="toolbar" style="padding-bottom: 0px;">
            <el-form :inline="true" :model="departmentQuery">
                <el-form-item>
                    <el-input v-model="departmentQuery.name" placeholder="姓名" size="small"></el-input>
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" v-on:click="loadData" size="small">查询</el-button>
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" @click="handleAdd" size="small">新增</el-button>
                </el-form-item>
            </el-form>
        </el-col>

        <!--列表-->
        <el-table :data="departments" highlight-current-row v-loading="listLoading"
                  border stripe @selection-change="selsChange" style="width: 100%;">
            <el-table-column type="selection" width="55"></el-table-column>
            <el-table-column type="index" width="60"></el-table-column>
            <el-table-column prop="name" label="部门名称" width="120" sortable></el-table-column>
            <el-table-column prop="sn" label="部门编号" width="120" sortable></el-table-column>
            <el-table-column prop="state" label="状态" width="100">
                <template scope="scope">
                    <b style="color: #12d30c;" v-if="scope.row.state==0">正常</b>
                    <b style="color: #d3241e;" v-else>禁用</b>
                </template>
            </el-table-column>
            <el-table-column prop="manager.username" label="部门经理" min-width="180"></el-table-column>
            <el-table-column prop="parent.name" label="上级部门" min-width="180"></el-table-column>
            <el-table-column label="操作" width="150">
                <!--
                    slot-scope="scope"  表示将当前行的json对象封装到scope变量中
                        可以scope.row来获取当前行的json对象数据
                -->
                <template scope="scope">
                    <el-button size="small" @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
                    <el-button type="danger" size="small" @click="handleDel(scope.$index, scope.row)">删除</el-button>
                </template>
            </el-table-column>
        </el-table>

        <!--分页工具条-->
        <el-col :span="24" class="toolbar">
            <el-button type="danger" @click="batchRemove" size="small" :disabled="this.sels.length===0">批量删除</el-button>
            <!--
                el-pagination 是ElementUI的分页组件
                    layout 布局
                        sizes 每页行数的下拉框
                        prev 上一页按钮
                        next 下一页按钮
                        pager 每一页的快速链接
                        jumper 提供一个输入框，输入一个页码后按回车，直接跳到某一页
                        total 显示总行数
                    current-change 当当前页码发生改变时触发的事件，就是翻页
                    current-page 当前页码
                    page-size 每页行数
                    total 总行数：需要在当前组件中定义一个属性与之绑定，然后页面挂载完毕后加载数据的回调函数中给这个属性赋值
                        elementui就会自动计算总页数
                        总页数 = total%page-size == 0 ? total/page-size : total/page-size + 1
            -->
            <el-pagination layout="prev, pager, next, total" @current-change="handleCurrentChange" :page-size="10" :total="total" style="float:right;">
            </el-pagination>
        </el-col>

        <!--模态框-->
        <el-dialog title="新增/编辑" v-model="dialogFormVisible" :close-on-click-modal="false">
            <el-form :model="formData" ref="formData" :rules="formDataRules">
                <el-form-item prop="name">
                    <el-input v-model="formData.name" auto-complete="off" placeholder="部门名称"></el-input>
                </el-form-item>
                <el-form-item prop="sn">
                    <el-input v-model="formData.sn" auto-complete="off" placeholder="部门编号"></el-input>
                </el-form-item>
                <!--<el-form-item prop="phone">
                    <el-input v-model="formData.phone" auto-complete="off" placeholder="联系电话"></el-input>
                </el-form-item>-->
                <el-row>
                    <el-col :span="12">
                        <el-form-item>
                            <el-select v-model="formData.manager_id" placeholder="请选择部门经理">
                                <el-option :key="null" label="无部门经理" :value="null"></el-option>
                                <el-option v-for="item in managers" :key="item.id" :label="item.username" :value="item.id"></el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item>
                            <el-select v-model="formData.parent_id" placeholder="请选择上级部门">
                                <el-option :key="null" label="无上级部门" :value="null"></el-option>
                                <el-option v-for="item in parents" v-if="item.id != editObjectId" :key="item.id" :label="item.name" :value="item.id"></el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-input v-model="formData.id" type="hidden"></el-input>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button @click.native="dialogFormVisible = false">取消</el-button>
                <el-button type="primary" @click.native="submit" :loading="submitLoading">提交</el-button>
            </div>
        </el-dialog>
    </section>
</template>

<script>
    import util from '../../common/js/util'
    //import NProgress from 'nprogress'
    //import { getUserListPage, removeUser, batchRemoveUser, editUser, addUser } from '../../api/api';

    export default {
        data() {
            /**
             * 自定义验证规则 验证手机号：在data函数内部return返回json对象之前
             *  value 就是使用当前自定义验证规则的输入框的值
             */
            var phoneValidator = (rule, value, callback) => {
                if(/^1[3-9][0-9]{9}$/.test(value)){
                    //正常了 验证通过了  直接调用一下callback 不传参数
                    callback();
                }else{
                    //失败了：调用callback函数，传递一个Error对象，内部是错误提示消息
                    callback(new Error('请输入正确的手机号！'));
                }
            }
            var departmentNameUnique = (rule, value, callback) => {
                //发送ajax请求
                this.$http.get("/department/findByName/"+value+"/"+this.formData.id).then(res => {
                    if(res.data){
                        callback(new Error('该部门名称已被占用！'));
                    }else{
                        callback();
                    }
                })
            }
            return {
                departmentQuery: {          //分页和高级查询的条件参数对象
                    name: '',
                    pageNo: 1,
                    pageSize: 10
                },
                departments: [],            //表格数据
                total: 0,                   //分页组件：总行数
                listLoading: false,         //表格数据加载状态
                sels: [],                   //表格中被选中的行
                dialogFormVisible: false,   //模态框界面是否显示
                submitLoading: false,       //表单提交状态
                editObjectId: null,         //当前正在编辑的对象的id
                formDataRules: {            //表单验证规则对象
                    /**
                     * name  表示声明了一个验证规则叫name
                     *  这个验证规则本身是一个json数组，表示当前验证规则内部可以写多个验证
                     *      required：表示是否必填
                     *      message：当你输入的内容不符合当前规则要求的时候，弹出的提示消息
                     *      trigger：触发器，表示什么时候触发当前验证  blur 表示失去焦点
                     *  除了可以验证必填之外，还可以有很多种验证规则：比如字符串长度范围、数字范围、日期、数组
                     */
                    name: [
                        { required: true, message: '请输入部门名称', trigger: 'blur' },
                        //{ min: 3, max: 5, message: '长度在 3 到 5 个字符', trigger: 'blur' },
                        { validator: departmentNameUnique, trigger:'blur'}
                    ],
                    sn: [
                        { required: true, message: '请输入部门编号', trigger: 'blur' }
                    ],
                    phone: [
                        { required: true, message: '请输入手机号', trigger: 'blur' },
                        { validator: phoneValidator, trigger: 'blur' }
                    ]
                },
                //模态框表单界面数据
                formData: {
                    id: null,
                    name: '',
                    sn: '',
                    state: 0,
                    manager_id: null,
                    phone: null,
                    parent_id: null
                },
                managers:[],                //部门经理下拉框
                parents:[],                 //上级部门下拉框
            }
        },
        methods: {
            //翻页事件：参数是翻页后的当前页码
            handleCurrentChange(val) {
                this.departmentQuery.pageNo = val;
                this.loadData();        //使用这个json对象作为请求参数去查询数据
            },
            //获取部门列表
            loadData() {
                this.listLoading = true;        //表格正在加载数据
                //NProgress.start();            //启动进度条
                //发送ajax请求
                this.$http.patch("/department", this.departmentQuery).then(res => {
                    this.listLoading = false;       //表格加载数据完毕
                    //NProgress.done();         //停止进度条
                    this.departments = res.data.list    //给组件属性赋值即可自动展示数据
                    this.total = res.data.total
                })
            },
            //删除
            handleDel: function (index, row) {
                this.$confirm('确认删除该记录吗?', '提示', {
                    type: 'warning'
                }).then(() => {
                    this.listLoading = true;
                    //NProgress.start();
                    let para = { id: row.id };
                    this.$http.delete("/department/" + row.id).then(res => {
                        this.listLoading = false;
                        //NProgress.done();
                        let {success,msg} = res.data
                        if(success){
                            this.$message.success(msg)
                            this.loadData();
                        }else{
                            this.$message.error(msg)
                        }
                    })
                })
            },
            //显示编辑界面
            handleEdit: function (index, row) {
                this.dialogFormVisible = true;
                this.formData = Object.assign({}, row);
                this.editObjectId = row.id
            },
            //显示新增界面
            handleAdd: function () {
                this.dialogFormVisible = true;
                this.editObjectId = null
                this.formData = {
                    id: null,
                    name: '',
                    sn: '',
                    state: 0,
                    manager_id: null,
                    parent_id: null
                }
            },
            //提交表单
            submit: function () {
                /**
                 * this.$refs 表示Vue框架中通过标签的ref属性来获取标签对象，等同于jQuery中的$("#...")
                 *  也就是说当前组件内部所有标签的ref属性不能重复，与id属性一样
                 * this.$refs 获取到当前组件内部所有的ref属性值对应的标签对象，返回一个标签对象数组
                 * this.$refs.formData  表示获取当前组件中ref属性等于formData的那一个标签对象
                 *  还可以这样写：this.$refs['formData']
                 * validate方法表示执行表单验证，内部传入一个回调函数（一般写成箭头函数），有一个参数表示表单验证的结果 是布尔类型的值
                 *  当当前表单内所有需要验证的输入框全部验证通过，这个结果才会为true；否则只要有任何一个验证失败，这个结果都是false
                 */
                this.$refs.formData.validate(valid => {
                    if (valid) {
                        //NProgress.start();
                        this.submitLoading = true;              //表单正在提交
                        //发送请求
                        this.$http.put("/department", this.formData).then(res => {
                            //NProgress.done();
                            this.submitLoading = false;         //表单提交完毕
                            let {success,msg} = res.data        //解构表达式
                            if(success){
                                this.$message.success(msg);
                                this.dialogFormVisible = false  //关闭模态框
                                this.loadData()                 //重新加载表格数据
                            }else{
                                this.$message.error(msg);
                            }
                        })
                    }
                });
            },
            selsChange: function (sels) {
                this.sels = sels;
            },
            //批量删除
            batchRemove: function () {
                var ids = this.sels.map(item => item.id).toString();
                this.$confirm('确认删除选中记录吗？', '提示', {
                    type: 'warning'
                }).then(() => {
                    this.listLoading = true;
                    //NProgress.start();
                    this.$http.delete("/department/batchRemove/"+ids).then(res => {
                        this.listLoading = false;
                        //NProgress.done();
                        let {success,msg} = res.data
                        if(success){
                            this.$message.success(msg)
                            this.loadData();
                        }else{
                            this.$message.error(msg)
                        }
                    })
                })
            }
        },
        mounted() {
            this.loadData();
            //发送请求查询部门经理，作为下拉框选项
            this.$http.get("/employee/findAllByJobId/5").then(res => {
                this.managers = res.data
            })
            //发送请求查询上级部门，作为下拉框选项
            this.$http.get("/department/findAllParent/1").then(res => {
                this.parents = res.data
            })
        }
    }

</script>

<style scoped>

</style>